namespace Web.Page.Rss
{
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Xml;

    using BLF.WWW_User;
    using Model.WWW_User;
    using Wuqi.Webdiyer;
    using BLF.WWW_WWW.Rss;
    using Model.WWW_WWW.Rss;

    public class GetRss : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //FormsAuthentication.SetAuthCookie("T000105868", false);
            if (Request.QueryString["do"] == null)
            {
                return;
            }
            string strDo = Request.QueryString["do"].ToString();
            if (strDo == "0")
            {
                GetRssData();
            }
            else if (strDo == "1")
            {
                SaveRssData();
            }
            else if (strDo == "2")
            {
                DelRssData();
            }
            else if (strDo == "3")
            {
                AddRss();
            }
            else if (strDo == "4")
            {
                GetSelectString();
            }
            else if (strDo == "5")
            {
                AddRssFeed();
            }
            else if (strDo == "6")
            {
                GetLearnandNative();
            }
            else if (strDo == "7")
            {
                UpdateContent();
            }
            else if (strDo == "8")
            {
                Subscribe();
            }
            else if (strDo == "9")
            {
                AddUserRss();
            }
        }

        private void AddUserRss()
        {
            Response.Clear();
            if (!(Page.User.Identity.Name == "" || Request.QueryString["url"] == null || Request["RssID"] == null || Request["ShowCount"] == null))
            {
                T_RssFeedSubscriptionDetails entity = new T_RssFeedSubscriptionDetails(Page.User.Identity.Name, Request.QueryString["url"].ToString(), "0", 4, "");
                if (RssFeedSubscription.InsertRssFeedSubscription(entity) == 1)
                {
                    Response.Clear();
                    Response.ContentType = "text/xml";
                    try
                    {
                        string key = Request["url"].ToString().ToLower().Trim();
                        int RssID = int.Parse(Request["RssID"].ToString());
                        int ShowCount = int.Parse(Request["ShowCount"].ToString());
                        string returnHtml;

                        string htmlError = GetGlobalResourceObject("Rss", "htmlError").ToString();
                        XmlDocument xmlDoc = (XmlDocument)Cache[key];
                        XmlNode channelNode;
                        XmlNodeList itemNodes;
                        if (xmlDoc == null)
                        {
                            try
                            {
                                xmlDoc = new XmlDocument();
                                xmlDoc.Load(key);
                                channelNode = xmlDoc.SelectNodes("/rss/channel").Item(0);
                                itemNodes = xmlDoc.SelectNodes("/rss/channel/item");
                                for (int i = 9; i < itemNodes.Count; i++)
                                {
                                    channelNode.RemoveChild(itemNodes.Item(i));
                                }
                                Cache.Insert(key, xmlDoc, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
                            }
                            catch
                            {
                                Response.Write(htmlError.Replace("#id", RssID.ToString()).Replace("#url", key).Replace("#0", key));
                                return;
                            }
                        }
                        XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                        nsmgr.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
                        nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
                        #region

                        string html1 = GetGlobalResourceObject("Rss", "html1").ToString();
                        string html2 = GetGlobalResourceObject("Rss", "html2").ToString();
                        string html3 = GetGlobalResourceObject("Rss", "html3").ToString();
                        string play = GetGlobalResourceObject("Rss", "play").ToString();
                        string mediaLink = GetGlobalResourceObject("Rss", "mediaLink").ToString();
                        //key = HttpUtility.UrlDecode(key);
                        channelNode = xmlDoc.SelectNodes("/rss/channel").Item(0);
                        itemNodes = xmlDoc.SelectNodes("/rss/channel/item");
                        for (int i = ShowCount; i < itemNodes.Count; i++)
                        {
                            channelNode.RemoveChild(itemNodes.Item(i));
                        }

                        string rss0 = "#";
                        string rss1 = "";
                        XmlNodeList tmps = xmlDoc.SelectNodes("/rss/channel/link");
                        if (tmps.Count > 0) rss0 = tmps[0].InnerText;
                        //rss0 = HttpUtility.UrlDecode(rss0);
                        tmps = xmlDoc.SelectNodes("/rss/channel/title");
                        if (tmps.Count > 0) rss1 = tmps[0].InnerText;
                        returnHtml = html1.Replace("#id", RssID.ToString()).Replace("#url", key).Replace("#0", rss0).Replace("#1", rss1);

                        itemNodes = xmlDoc.SelectNodes("/rss/channel/item");
                        string item0 = "", item1 = "#", item2 = "", item3 = "", item4 = "";
                        bool mp3Falg = false;
                        for (int i = 0; i < itemNodes.Count; i++)
                        {
                            item0 = ""; item1 = "#"; item2 = ""; item3 = ""; item4 = ""; mp3Falg = false;
                            tmps = itemNodes.Item(i).SelectNodes("title");
                            if (tmps.Count > 0) item0 = tmps[0].InnerText;

                            tmps = itemNodes.Item(i).SelectNodes("link");
                            if (tmps.Count > 0) item1 = tmps[0].InnerText;
                            if (item1 == "#")
                            {
                                tmps = itemNodes.Item(i).SelectNodes("guid");
                                if (tmps.Count > 0) item1 = tmps[0].InnerText;
                            }
                            //item1 = HttpUtility.UrlDecode(item1);

                            tmps = itemNodes.Item(i).SelectNodes("description");
                            if (tmps.Count > 0) item2 = tmps[0].InnerText;
                            if (item2 == "")
                            {
                                tmps = itemNodes.Item(i).SelectNodes("content:encoded", nsmgr);
                                if (tmps.Count > 0) item2 = tmps[0].InnerText;
                            }

                            tmps = itemNodes.Item(i).SelectNodes("pubDate");
                            if (tmps.Count > 0) item3 = tmps[0].InnerText;
                            if (item3 == "")
                            {
                                tmps = itemNodes.Item(i).SelectNodes("dc:date", nsmgr);
                                if (tmps.Count > 0) item3 = tmps[0].InnerText;
                            }

                            tmps = itemNodes.Item(i).SelectNodes("enclosure");
                            if (tmps.Count > 0) item4 = tmps[0].Attributes["url"].Value;
                            if (item4.EndsWith(".mp3")) mp3Falg = true;

                            int t = item3.IndexOf(":");
                            if (t > 1) item3 = item3.Substring(0, t);
                            if (item0.Length < 120)
                            {
                                string a = Regex.Replace(item2, "<(.|\n)+?>", "");
                                int b = (120 - item0.Length);
                                if (a.Length < b)
                                {
                                    item0 = item0 + "&nbsp;<span class=\"RssFont\">" + a + "</span>";
                                }
                                else
                                {
                                    item0 = item0 + "&nbsp;<span class=\"RssFont\">" + a.Substring(0, b) + "</span>";
                                }
                            }

                            returnHtml += html2.Replace("#id", RssID.ToString()).Replace("url", key).Replace("#sort", i.ToString()).Replace("#0", item0).Replace("#1", item1).Replace("#2", item2).Replace("#3", item3);
                            if (mp3Falg)
                            {
                                returnHtml = returnHtml.Replace("#4", (play + mediaLink).Replace("#0", item4).Replace("#id", RssID.ToString()).Replace("#sort", i.ToString()));
                            }
                            else if (item4.Trim() != "")
                            {
                                returnHtml = returnHtml.Replace("#4", mediaLink.Replace("#0", item4));
                            }
                            else
                            {
                                returnHtml = returnHtml.Replace("#4", "");
                            }
                        }
                        returnHtml += html3;
                        //returnHtml = returnHtml.Replace("\n", "").Replace("\r", "").Replace("\t", "");
                        #endregion
                        Response.Write(returnHtml);
                    }
                    catch { }
                    //Response.Write("1");
                }
                return;
            }
            Response.Write("0");
        }       

        private void Subscribe()
        {
            Response.Clear();
            if (!(Page.User.Identity.Name == "" || Request.QueryString["url"] == null))
            {
                T_RssFeedSubscriptionDetails entity = new T_RssFeedSubscriptionDetails(Page.User.Identity.Name,
                    Request.QueryString["url"].ToString(), "1", 4, "");
                if (RssFeedSubscription.InsertRssFeedSubscription(entity) != -1)
                {
                    Response.Write("1");
                    return;
                }
            }
            Response.Write("0");
        }

        private void UpdateContent()
        {
            Response.Clear();
            if (!(Page.User.Identity.Name == "" || Request.QueryString["pageIndex"] == null || Request.QueryString["learnSel"] == null || Request.QueryString["nativeSel"] == null || Request.QueryString["pageSize"].ToString().Trim() == ""))
            {
                string where = "CatID<>1";
                if (Request.QueryString["learnSel"].ToString() != "All") where += " and (LanguageLearn='" + Request.QueryString["learnSel"].ToString() + "' or LanguageLearn='All')";
                if (Request.QueryString["nativeSel"].ToString() != "All") where += " and (LanguageSpeak='" + Request.QueryString["nativeSel"].ToString() + "' or LanguageSpeak='All')";
                int recordCount = 0;
                int pageIndex = int.Parse(Request.QueryString["pageIndex"].ToString());
                int pageSize = int.Parse(Request.QueryString["pageSize"].ToString());
                List<RssFeed> list = RssFeed.GetRssFeed(where, "ID", pageIndex, pageSize, out recordCount);
                DataTable dt = RssFeedSubscription.GetRssFeedSubscription(Page.User.Identity.Name);
                if (list.Count > 0)
                {
                    string content1 = GetGlobalResourceObject("Rss", "content1").ToString();
                    string content2 = GetGlobalResourceObject("Rss", "content2").ToString();
                    string page = GetGlobalResourceObject("Rss", "page").ToString();
                    string page1 = GetGlobalResourceObject("Rss", "page1").ToString();
                    string page2 = GetGlobalResourceObject("Rss", "page2").ToString();
                    StringBuilder sb = new StringBuilder();
                    XmlDocument xmlDoc;
                    string key;
                    XmlNode channelNode;
                    XmlNodeList itemNodes;
                    #region
                    foreach (RssFeed item in list)
                    {
                        key = item.RSSURL.Trim().ToLower();
                        xmlDoc = (XmlDocument)Cache[key];
                        if (xmlDoc == null)
                        {
                            try
                            {
                                xmlDoc = new XmlDocument();
                                xmlDoc.Load(key);
                                channelNode = xmlDoc.SelectNodes("/rss/channel").Item(0);
                                itemNodes = xmlDoc.SelectNodes("/rss/channel/item");
                                for (int i = 9; i < itemNodes.Count; i++)
                                {
                                    channelNode.RemoveChild(itemNodes.Item(i));
                                }
                                Cache.Insert(key, xmlDoc, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
                            }
                            catch { continue; }
                        }

                        string rss0 = "#";
                        string rss1 = "";
                        string rss2 = "";
                        XmlNodeList tmps = xmlDoc.SelectNodes("/rss/channel/link");
                        if (tmps.Count > 0) rss0 = tmps[0].InnerText;
                        tmps = xmlDoc.SelectNodes("/rss/channel/title");
                        if (tmps.Count > 0) rss1 = tmps[0].InnerText;
                        tmps = xmlDoc.SelectNodes("/rss/channel/description");
                        if (tmps.Count > 0) rss2 = tmps[0].InnerText;
                        if (HaveRssUrl(dt, key))
                        {
                            sb.Append(content2.Replace("#0", rss1).Replace("#1", rss2).Replace("#2", rss0).Replace("#3", item.RSSURL).Replace("#4", key));
                        }
                        else
                        {
                            sb.Append(content1.Replace("#0", rss1).Replace("#1", rss2).Replace("#2", rss0).Replace("#3", item.RSSURL).Replace("#4", key));
                        }
                    }//for
                    #endregion
                    int pageCount = (int)Math.Ceiling((decimal)recordCount / (decimal)pageSize);
                    if (pageCount > 1)
                    {
                        sb.Append(page1);
                        int start = 1, end = 20;
                        start = pageIndex - 10;
                        end = pageIndex + 10;
                        if (start < 1) start = 1;
                        if (end > pageCount) end = pageCount;
                        for (int i = 1; i < end + 1; i++)
                        {
                            sb.Append(page.Replace("#0", i.ToString()));
                        }
                        sb.Append(page2);
                    }
                    Response.Write(sb.ToString());
                }
                return;
            }
            Response.Write("0");
        }

        private bool HaveRssUrl(DataTable dt, string key)
        {
            foreach (DataRow dr in dt.Rows)
            {
                if (dr[0].ToString().Trim().ToLower() == key.ToLower().Trim()) return true;
            }
            return false;
        }

        private void AddRssFeed()
        {
            Response.Clear();
            if (!(Page.User.Identity.Name == "" || Request.QueryString["url"] == null || Request.QueryString["learnSel"] == null || Request.QueryString["nativeSel"] == null || Request.QueryString["do"].ToString().Trim() == ""))
            {
                T_RssFeedDetails entity = new T_RssFeedDetails(0, Request.QueryString["url"].ToString(), Request.QueryString["learnSel"].ToString(), Request.QueryString["nativeSel"].ToString(), "", false, 0, true, Page.User.Identity.Name, 0);
                if (RssFeed.InsertRssFeed(entity) >0)
                {
                    Response.Write("1");
                }
                return;
            }
            Response.Write("0");
        }

        private void DelRssData()
        {
            Response.Clear();
            if (!(Page.User.Identity.Name == "" || Request.QueryString["url"] == null || Request.QueryString["do"].ToString().Trim() == ""))
            {
                if (RssFeedSubscription.DeleteRssFeedSubscription(Page.User.Identity.Name, Request.QueryString["url"].ToString())>0)
                {
                    Response.Write("1");
                }
                else
                {
                    Response.Write("0");
                }
                return;
            }
            Response.Write("0");
        }

        private void SaveRssData()
        {
            Response.Clear();
            if (!(Page.User.Identity.Name == "" || Request.QueryString["url"] == null || Request.QueryString["do"].ToString().Trim() == "" || Request.QueryString["ShowCount"].ToString().Trim() == ""))
            {
                if (RssFeedSubscription.UpdateRssFeedSubscription(Page.User.Identity.Name, Request.QueryString["url"].ToString(), int.Parse(Request.QueryString["ShowCount"].ToString())) >0)
                {
                    Response.Write("1");
                }
                else
                {
                    Response.Write("0");
                }
                return;
            }
            Response.Write("0");
        }

        private void GetRssData()
        {
            Response.Clear();
            Response.ContentType = "text/xml";
            Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            Response.Write("<Rss>");
            if (Page.User.Identity.Name == "")
            {
                WriteInitRss();
            }
            else
            {
                DataTable dt = RssFeedSubscription.GetRssFeedSubscription(Page.User.Identity.Name);
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        Response.Write(string.Format("<RssItem rssUrl=\"{0}\" ShowCount=\"{1}\" Type=\"{2}\"/>", dr[0].ToString(), dr[1].ToString(), dr[2].ToString()));
                    }
                }
                else
                {
                    WriteInitRss();
                }
            }
            Response.Write("</Rss>");
        }

        private void WriteInitRss()
        {
            Response.Write("<RssItem rssUrl=\"\" ShowCount=\"0\" Type=\"1\"/>");
        }

        private void AddRss()
        {
            Response.Clear();
            if (!(Page.User.Identity.Name == "" || Request.QueryString["url"] == null || Request.QueryString["do"].ToString().Trim() == ""))
            {
                T_RssFeedSubscriptionDetails entity = new T_RssFeedSubscriptionDetails(Page.User.Identity.Name, Request.QueryString["url"].ToString(), "1", 4, "");
                if (RssFeedSubscription.InsertRssFeedSubscription(entity) > 0)
                {
                    Response.Write("1");
                    return;
                }
            }
            Response.Write("0");
        }

        private DataTable GetDTFromXml(string fileName)
        {
            DataSet ds = new DataSet();
            try
            {
                ds.ReadXml(Server.MapPath(String.Format("/Control/{0}/{1}", Lx.Web.Common.UI.Globals.Language, fileName)));
                return ds.Tables[0];
            }
            catch
            {
                try
                {
                    ds.ReadXml(Server.MapPath(String.Format("/Control/en-us/{0}", fileName)));
                    return ds.Tables[0];
                }
                catch
                {
                    ds.ReadXml(Server.MapPath(String.Format("/Control/zh-cn/{0}", fileName)));
                    return ds.Tables[0];
                }
            }
        }

        private void GetSelectString()
        {
            Response.Clear();
            try
            {
                if (!(Request.QueryString["selectName"] == null || Request.QueryString["fileName"] == null || Request.QueryString["valueIndex"] == null || Request.QueryString["textIndex"] == null || Request.QueryString["do"].ToString().Trim() == ""))
                {
                    string selectName = Request.QueryString["selectName"].ToString();
                    string fileName = Request.QueryString["fileName"].ToString();
                    int valueIndex = int.Parse(Request.QueryString["valueIndex"].ToString());
                    int textIndex = int.Parse(Request.QueryString["textIndex"].ToString());
                    DataTable dt = GetDTFromXml(fileName);
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<select id=\"");
                    sb.Append(selectName);
                    sb.Append("\">");
                    if (Request.QueryString["AddValue"] != null && Request.QueryString["AddText"] != null)
                    {
                        sb.Append("<option value=\"");
                        sb.Append(Request.QueryString["AddValue"].ToString());
                        sb.Append("\">");
                        sb.Append(Request.QueryString["AddText"].ToString());
                        sb.Append("</option>");
                    }
                    foreach (DataRow dr in dt.Rows)
                    {
                        sb.Append("<option value=\"");
                        sb.Append(dr[valueIndex].ToString());
                        sb.Append("\">");
                        sb.Append(dr[textIndex].ToString());
                        sb.Append("</option>");
                    }
                    sb.Append("</select>");
                    Response.Write(sb.ToString());
                    return;
                }
            }
            catch { }
            Response.Write("0");
        }

        private void GetLearnandNative()
        {
            Response.Clear();
            if (Page.User.Identity.Name == "")
            {
                Response.Write("English,Chinese");
            }
            else
            {
                Response.Write(RssFeedSubscription.GetLanguage(Page.User.Identity.Name));
            }
        }
    }
}